package com.aysafety.iotdataplatformserver.configurer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.aysafety.iotdataplatformserver.listener.DataListener;

import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

@Component
@ChannelHandler.Sharable
public class IotDataPlatformServerHandler extends ChannelInboundHandlerAdapter {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    DataListener dataListener;

    @Override public void channelActive(ChannelHandlerContext ctx) throws Exception {
        dataListener.connection(ctx);
    }

    @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        dataListener.close(ctx);
    }

    @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        try {
            String msgString = "{status: 200}";
            dataListener.distribute(msg, ctx);
            ctx.writeAndFlush(msgString).addListener(ChannelFutureListener.CLOSE);
        } catch (Exception e) {
            String errorCode = "{status: 500}";
            logger.info("接收数据错误", e);
            ctx.writeAndFlush(errorCode).addListener(ChannelFutureListener.CLOSE);
        }
    }

    @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
